package mk.company.fin.service;

import java.util.Locale;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import mk.company.fin.model.User;

/**
 * Service for locales manipulation. Keeps the current chosen locale.
 * 
 * @author vlado.gjorgjiev
 */
@Service
public class LocaleService {

	private Locale currentLocale = new Locale("mk");

	
	public Locale getCurrentLocale() {
		return currentLocale;
	}

	public void setCurrentLocale(Locale currentLocale) {
		this.currentLocale = currentLocale;
	}
	
	public boolean isCurrentLocaleEqual(Locale targetLocale) {
		return currentLocale != null && targetLocale != null &&
				currentLocale.equals(targetLocale);
	}
	
	/**
	 * Gets the default locale for the given user depending on the
	 * user's language. 
	 * If the locale is not set for the user or doesn't exist
	 * then the default JVM locale is returned.
	 * 
	 * @param user the user
	 * @return user or JVM locale
	 */
	public Locale getUserLocale(User user) {
		Locale result = null;
		String language = user.getLanguage();
		if (StringUtils.isNotBlank(language)) {
			result = new Locale(language);
		}
		
		// fall-back
		if (result == null) {
			result = Locale.getDefault();
		}
		return result;
	}
}
